package ${servicePackage};

import com.douya.common.ex.EmptyResultException;
import com.douya.common.ex.ApiException;
import com.douya.common.enums.CommonResultEnums;
import com.douya.common.pojo.dto.PagerDTO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.douya.common.utils.BeanUtils;
import ${dtoPackage}.${class}DTO;
import ${voPackage}.${class}VO;
import ${mapperPackage}.${class}Mapper;
import ${doPackage}.${class}DO;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 说明：${remarks}服务类
 *
 * @author ${author}
 * @date ${date}
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class ${class}Service {

    @Resource
    ${class}Mapper m${class}Mapper;

    /**
     * 分页获取${remarks}
     *
     * @param pager 分页条件
     * @return 分页信息
     */
    public IPage${r'<'}${class}VO> page(PagerDTO pager) {
        ${class}DO m${class} = new ${class}DO();
        IPage<${class}DO> selectPage = m${class}Mapper.selectPage(
        pager.toPage(m${class}),pager.toQuery(m${class}));
            return selectPage.convert(
            item -> BeanUtils.born(item, ${class}VO.class));
    }

    /**
     * 根据ID获取${remarks}的VO对象
     *
     * @param id ID
     * @return ${remarks}，匹配不到抛出异常
     */
    public ${class}VO findById(Long id) {
        ${class}DO ${name} = m${class}Mapper.selectById(id);
        if (${name} == null) {
            throw new EmptyResultException();
        }
        return BeanUtils.born(${name}, ${class}VO.class);
    }

    /**
     * 新增/修改${remarks}
     *
     * @param ${name}DTO ${remarks}
     */
    @Transactional(rollbackFor = Throwable.class)
    public void insert(${class}DTO ${name}DTO) {
        ${class}DO ${name}DO;
        if (${name}DTO.getId() != null) {
            ${name}DO = m${class}Mapper.selectById(${name}DTO.getId());
            if (${name}DO == null) {
                throw new ApiException("ID无法匹配", CommonResultEnums.INVALID_PARAMS.getCode());
            }
            BeanUtils.copyProperties(${name}DTO, ${name}DO);
            m${class}Mapper.updateById(${name}DO);
        } else {
            ${name}DO = new ${class}DO();
            BeanUtils.copyProperties(${name}DTO, ${name}DO);
            m${class}Mapper.insert(${name}DO);
        }
    }

    /**
     * 根据ID删除${remarks}
     *
     * @param id ID
     */
    @Transactional(rollbackFor = Throwable.class)
    public void delete(Long id) {
        m${class}Mapper.deleteById(id);
    }

}
